package org.example.gradleauth.util;

import gradle.common.core.mode.entity.SystemPermissions;

import java.util.*;

public class PermissionsUtil {


    /**
     * 给定权限列表和角色拥有的权限 ID，返回最终权限集合（包含子权限）
     */
    public static Set<SystemPermissions> getAllInheritedPermissions(List<SystemPermissions> allPermissions, Set<Long> rolePermissionIds) {
        // 1. 构建 parentId -> children 映射
        Map<Long, List<SystemPermissions>> parentChildrenMap = new HashMap<>();
        Map<Long, SystemPermissions> idPermissionMap = new HashMap<>();
        for (SystemPermissions perm : allPermissions) {
            parentChildrenMap
                    .computeIfAbsent(perm.getParentId(), k -> new ArrayList<>())
                    .add(perm);
            idPermissionMap.put(perm.getId(), perm);
        }

        // 2. 收集结果（防止重复）
        Set<Long> visitedIds = new HashSet<>();
        Set<SystemPermissions> result = new HashSet<>();

        for (Long id : rolePermissionIds) {
            collectChildren(id, parentChildrenMap, idPermissionMap, visitedIds, result);
        }

        return result;
    }

    /**
     * 递归查找所有子权限
     */
    private static void collectChildren(Long id,
                                        Map<Long, List<SystemPermissions>> parentChildrenMap,
                                        Map<Long, SystemPermissions> idPermissionMap,
                                        Set<Long> visited,
                                        Set<SystemPermissions> result) {
        // 避免重复或死循环
        if (!visited.add(id)) return;

        SystemPermissions perm = idPermissionMap.get(id);
        if (perm != null) {
            result.add(perm);
        }

        List<SystemPermissions> children = parentChildrenMap.getOrDefault(id, Collections.emptyList());
        for (SystemPermissions child : children) {
            collectChildren(child.getId(), parentChildrenMap, idPermissionMap, visited, result);
        }
    }

}
